<?php


namespace app\admin\model;


use AlibabaCloud\Client\AlibabaCloud;

class AliSMS
{
    // 用户识别号
    private $accessKeyId;
    // 验证秘钥
    private $accessKeySecret;
    // 区域ID
    private $regionId;
    // 短信签名
    private $signName;
    // 模板ID
    private $templateCode=[
        0=>'SMS_194915317',//验证码  code
        1=>'SMS_194900290',//服务通知 burial_time
        2=>'SMS_194915304',//迁出通知 move_time
        3=>'SMS_194910386',//寄存通知 deposit_time
        4=>'SMS_194915318',//退款通知 tomb_num
        5=>'SMS_194920285',//续费通知 tomb_num
    ];

    /**
     * 初始化
     * AliSMS constructor.
     * @throws \AlibabaCloud\Client\Exception\ClientException
     */
    public function __construct( )
    {
        // 用户标识号
        $this->accessKeyId = "LTAIhSMfWPMHM4F3";
        // 验证秘钥
        $this->accessKeySecret = "sBZ9LUbpEBbCTQfSgS4nWAxNT0gaYq";
        // 区域ID
        $this->regionId = "cn-hangzhou";
        // 短信签名
        $this->signName = "寿南山";

        // 初始化SDK
        AlibabaCloud::accessKeyClient($this->accessKeyId, $this->accessKeySecret)
            ->regionId($this->regionId)
            ->asDefaultClient();
    }

    // 发送 服务通知
    public   function sendServiceNoticeSms($tempCode,$mobile,$tempParam=[],&$errorMsg = ''){
        // 模板替换标签
        $templateParam = json_encode($tempParam, JSON_UNESCAPED_UNICODE);
        // 发送参数
        $param = [
            'RegionId' => $this->regionId,
            'PhoneNumbers' => $mobile,
            'TemplateType' => "1",
            'SignName' => $this->signName,
            'TemplateCode' => $this->templateCode[$tempCode],
            'TemplateParam' => "$templateParam"
        ];
        // 执行发送类
        $result = self::sendSdk($param);

        file_put_contents(RUNTIME_PATH . "/sms.txt", json_encode($param));
        // 错误信息
        $errorMsg = isset($result['Message']) ? $result['Message'] : '';
        // 返回结果
        if (strtoupper($result['Code']) === 'OK') {
            // 发送成功
            return true;
        } else {
            // 发送失败
            return false;
        }
    }

    /**
     * 发送短信
     * @param $mobile 手机号码
     * @param $code 6位数验证码
     * @param string $errorMsg 错误信息
     * @return bool 返回结果：true成功，false失败
     */
    public  function sendSms($mobile,  &$errorMsg = ''){
        $code  =  cmf_get_verification_code($mobile);// 发送验证码
        // 模板替换标签
        $templateParam = json_encode(['code' => $code], JSON_UNESCAPED_UNICODE);
        // 发送参数
        $param = [
            'RegionId' => $this->regionId,
            'PhoneNumbers' => $mobile,
            'SignName' => $this->signName,
            'TemplateCode' => $this->templateCode[0],
            'TemplateParam' => "$templateParam"
        ];
        if ($code){
            // 执行发送类
            $result = self::sendSdk($param);
            file_put_contents(RUNTIME_PATH . "/sms.txt", json_encode($param));
            // 错误信息
            $errorMsg = isset($result['Message']) ? $result['Message'] : '';
            // 返回结果
            if (strtoupper($result['Code']) === 'OK') {
                 cmf_verification_code_log($mobile,$code); // 记录验证码
                // 发送成功
                return true;
            } else {
                // 发送失败
                return false;
            }
        }else{
            $errorMsg = '验证码错误';
            return false;
        }
    }

    /**
     * 调用SDK发送短信
     * @param $param
     * @return array
     * @throws \AlibabaCloud\Client\Exception\ClientException
     * @throws \AlibabaCloud\Client\Exception\ServerException
     * @author 牧羊人
     * @date 2019/11/5
     */
    public static function sendSdk($param)
    {
        try {
            $result = AlibabaCloud::rpc()
                ->product('Dysmsapi')
                // ->scheme('https') // https | http
                ->version('2017-05-25')
                ->action('SendSms')
                ->method('POST')
                ->host('dysmsapi.aliyuncs.com')
                ->options(['query' => $param])
                ->request();
            //$res['Message'] == 'OK' && $res['Code'] == 'OK'   发送成功
            return $res = $result->toArray();
        } catch (ClientException $e) {
            return ['Code' => 'Error', 'Message' => $e->getErrorMessage()];
        } catch (ServerException $e) {
            return ['Code' => 'Error', 'Message' => $e->getErrorMessage()];
        }
    }

}